package com.turing.post.thirdinterface.impl;

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;

import com.turing.post.tuxedo.util.TuxedoRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

import cz.dhl.ftp.Ftp;
import cz.dhl.ftp.FtpConnect;
import cz.dhl.ftp.FtpFile;
import cz.dhl.ftp.FtpInputStream;

public class PSPCBankAccFile {
	
	
	/**
	 * 通过ftp获取远程文件
	 * 
	 * @param ftpaddress
	 * @param filename
	 * @return
	 * @throws PCPSApplicationException
	 */
	@SuppressWarnings("unused")
	private byte[] getRemoteFile(String ftpaddress, String filename)
			throws PCPSApplicationException {
		BufferedInputStream bis = null;
		Ftp cl = new Ftp();
		List<byte[]> abuf = new ArrayList<byte[]>();
		int totalsz = 0;
		try {
			boolean bret = cl.connect(FtpConnect.newConnect(ftpaddress));
			PCPSUtil.Log(ftpaddress + " 连接返回 " + bret);
			/* source FtpFile remote file */
			FtpFile file = new FtpFile(filename, cl);
			/* open ftp input stream */
			bis = new BufferedInputStream(new FtpInputStream(file));

			while (true) {
				byte[] buf = new byte[4096];
				int sz = bis.read(buf);
				if (sz > 0) {
					if (sz == buf.length)
						abuf.add(buf);
					else {
						byte[] bbuf = new byte[sz];
						System.arraycopy(buf, 0, bbuf, 0, sz);
						abuf.add(bbuf);
					}
					totalsz += sz;
				} else
					break;
			}
			bis.close();
			bis = null;
			cl.disconnect();
			cl = null;
		} catch (Exception e) {
			PCPSUtil.Log("FTP CHKACC FAILED", e);
			throw new PCPSApplicationException(TuxedoRespCode.RC_ACCCHKFILE,
					"FTP CHKACC FAILED!");
		} finally {
			try {
				if (bis != null)
					bis.close();
			} catch (Exception e) {
			}

			try {
				if (cl != null)
					cl.disconnect();
			} catch (Exception e) {
			}
		}

		if (totalsz <= 0)
			throw new PCPSApplicationException(TuxedoRespCode.RC_ACCCHKFILE,
					"FTP CHKACC SIZE <= 0 FAILED!");

		byte[] content = new byte[totalsz];
		int pos = 0;

		for (byte[] al : abuf) {
			System.arraycopy(al, 0, content, pos, al.length);
			pos += al.length;
		}

		return (content);
	}
}
